package com.whiteape.book.net;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import me.jessyan.progressmanager.ProgressManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RetrofitHelper {

    private Map<String, HttpApi> httpApiImplMap = new HashMap<>();
    private static RetrofitHelper instance;


    private final OkHttpClient.Builder builder = new OkHttpClient.Builder()

            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
            .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS);//.build();
    private final OkHttpClient client = ProgressManager.getInstance().with(builder).build();

    private RetrofitHelper() {
    }

    public static RetrofitHelper getInstance() {
        if (null == instance) {
            instance = new RetrofitHelper();
        }
        return instance;
    }


    public HttpApi getHttpApiImpl(String baseUrl) {
        if (httpApiImplMap.containsKey(baseUrl)) {
            return httpApiImplMap.get(baseUrl);
        }
        HttpApi apiImpl = new Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)
                .addConverterFactory(EncodeConverter.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(HttpApi.class);
        httpApiImplMap.put(baseUrl, apiImpl);
        return apiImpl;

    }
}
